import os
import base64

import cv2
import numpy as np


def to_byte(size, unit):
    if unit == 'b':
        loop_times = 0
    elif unit == 'K':
        loop_times = 1
    elif unit == 'M':
        loop_times = 2
    elif unit == 'G':
        loop_times = 3
    else:
        raise Exception('Unsupported unit')
    base = 1
    for i in range(loop_times):
        base *= 1024
    return base * size


# 生成太大的图片很卡而且报错（1G），200M没问题
def generate_img(path, size, unit='M'):
    fix_h = 256
    size = to_byte(size, unit)
    a = size // fix_h
    if a != 0:
        b = sum(map(int, str(a)))
        c = 3 - b % 3
        a += c
        size += c * fix_h
    d = a // 3

    randomByteArray = bytearray(os.urandom(size))
    flatNumpyArray = np.array(randomByteArray)

    bgrImage = flatNumpyArray.reshape(fix_h, d, 3)
    # imwrite不支持路径中包含中文
    # cv2.imwrite(path, bgrImage)
    cv2.imencode('.png', bgrImage)[1].tofile(path)


# 生成太大的图片很卡而且报错（1G），200M没问题
def generate_img2(path, size, unit='M'):
    # fix_h = 256
    # size = to_byte(size, unit)
    # a = size // fix_h
    # if a != 0:
    #     b = sum(map(int, str(a)))
    #     c = 3 - b % 3
    #     a += c
    #     size += c * fix_h
    # d = a // 3

    # randomByteArray = bytearray(os.urandom(size))
    # randomByteArray = [
    #     0, 1, 1, 0,
    #     1, 0, 1, 0,
    #     1, 1, 0, 0,
    #     0, 0, 0, 0,
    #
    #     0, 1, 1, 0,
    #     0, 1, 1, 0,
    #     0, 1, 1, 0,
    #     0, 1, 1, 0,
    #
    #     1, 1, 1, 0,
    #     1, 1, 1, 0,
    #     1, 1, 1, 0,
    #     1, 1, 1, 0,
    #
    #     1, 1, 1, 0,
    #     1, 1, 1, 0,
    #     1, 1, 1, 0,
    #     1, 1, 1, 0,
    #
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    #
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    #
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    #     1, 1, 1, 1,
    # ]
    randomByteArray = bytearray(os.urandom(10000 * 3))
    for i in range(209+34):
        randomByteArray[i] = 0
    flatNumpyArray = np.array(randomByteArray)

    bgrImage = flatNumpyArray.reshape(100, 100, 3)
    # imwrite不支持路径中包含中文
    cv2.imwrite(path, bgrImage)
    # cv2.imencode('.png', bgrImage)[1].tofile(path)
    # cv2.imshow('BGRA', bgrImage)
    #
    # cv2.waitKey(0)

if __name__ == '__main__':
    mmm = to_byte(int(1), 'M')
    # mmm = 10
    # generate_img2('d:/1.png', 1, 'M')
    random_bytes = os.urandom(mmm)
    a = base64.b64encode(random_bytes)
    # print(a)
    # print(str(a, 'utf-8'))
    with open('d:/1.txt', 'w') as f:
        f.write(str(a, 'utf-8'))
    pass




